package com.spi.soconversion.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.spi.soconversion.base.SOCException;


/*
 * Class which gives a static Connection object. 
 * Do not forget call the closeConnection() after using the connection.
 * 
 * @author Abhilash Naik, SPI
 * */
public class DBConnection {
	private static Connection con; 
	public static Connection getConnection(String host, String Service, String user, String password) throws SOCException{
		try {
			if(null==con)
			{
				Class.forName(SOCConstants.ORACLE_DRIVER_CLASSNAME);
				con = DriverManager.getConnection(SOCConstants.DATABASE_HOST+host+SOCConstants.COLON+Service,user , password);
			}
		} catch (SQLException se) {
			throw new SOCException(
            		ErrorMessageReader.getError(
            				ErrorConstants.FAILED_DATABASE_CONNECTION),se);
		} catch (ClassNotFoundException ce) {
			throw new SOCException(
            		ErrorMessageReader.getError(
            				ErrorConstants.FAILED_ORACLE_DRIVER_SEARCH),ce);
		}
		
		return con;
	}
	
	public static void closeConnection() throws SOCException{
		try {
			con.close();
		} catch (SQLException se) {
			throw new SOCException(
            		ErrorMessageReader.getError(
            				ErrorConstants.FAILED_CLOSE_CONNECTION),se);
		}
	}
	
	public static Connection getConnection() throws SOCException{
		if(con==null)
		{
			throw new SOCException(
            		ErrorMessageReader.getError(
            				ErrorConstants.INVALID_GET_CONNECTION));
		}
		return con;
				
	}
}
